package com.cl.blog.aspect;

import com.cl.blog.annotation.Permissions;
import com.cl.blog.common.Const;
import com.cl.blog.common.Result;
import com.cl.blog.entity.BAdmin;
import com.cl.blog.entity.BRole;
import com.cl.blog.exception.WebException;
import com.cl.blog.service.BAdminService;
import com.cl.blog.service.BRoleService;
import com.cl.blog.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @Author 付
 * @Date 2024-04-27 15:22
 * @Version 1.0
 * @description
 * @since 1.0
 */
@Component
@Aspect
@Slf4j
public class PermissionsRoleAspect {
	@Autowired
	JwtUtil jwtUtil;

	@Autowired
	BRoleService bRoleService;
	@Autowired
	BAdminService bAdminService;

	@Pointcut("@annotation(permissions)")
	public void pointCut(Permissions permissions) {
	}

	@Around("pointCut(permissions)")
	public Object around(ProceedingJoinPoint point, Permissions permissions) throws Throwable {
		// 这里不能直接获取request，需要转型获取
		ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = requestAttributes.getRequest();
		String token = request.getHeader("token");
		Claims claim = jwtUtil.getClaimByToken(token, Const.GRADE_ADMIN);
		BAdmin bAdmin = bAdminService.getById(Integer.valueOf(claim.getSubject()));
		// 获取注解传入的权限等级
		int[] role = permissions.role();
		// 获取用户权限
		BRole bRole = bRoleService.getById(bAdmin.getRoleId());
		System.out.println("执行了权限判定切面—---"+bRole);
		long count = Arrays.stream(role).filter(item -> item == bRole.getRole()).count();
		if (count<=0){
			throw new WebException("抱歉，权限不足");
		}
		// 执行切点方法
		return point.proceed();
	}
}
